

local db_monitor = require("luastar.db.monitor")
local RedisConnector = require "resty.redis.connector"
local Redis = Class("com.ea.db.redis")
----local logger=logger;

function Redis:init(datasource)
    self.datasource = _.defaults(datasource, {
        host = "127.0.0.1",
        port = "6379",
        auth = nil,
        timeout = 30000,
        max_idle_timeout = 60000,
        pool_size = 50
    })
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Redis:init] datasource : ", cjson.encode(self.datasource))) end
end

function Redis:getConnect()
    
    local rc=RedisConnector:new();
    local redisparams = self.datasource;
    if not redisparams.connect_timeout then
      rc:set_connection_timeout(redisparams.connect_timeout)
    end
    if not redisparams.read_timeout then
      rc:set_read_timeout(redisparams.read_timeout);
    end
    
    local r,err=rc:connect(redisparams);
   
    if not r then
       ngx.log(ngx.ERR,logger.formatMsg( "[Redis:getConnect] failed to connect redis : ",err))
       return nil,"cannot connect to redis " .. err
    else
       db_monitor.add("redis_connect")
       if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Redis:getConnect] redis connected"))        end
       if self.datasource.pool_size <= 0 then      
            -- 将连接放入到连接池中，下次申请直接从连接池中获取
            local ok, err = r:set_keepalive(self.datasource.max_idle_timeout, self.datasource.pool_size)
           if not ok then
              ngx.log(ngx.ERR, logger.formatMsg("[Redis:getConnect] set keepalive failed : ", err))
           else
              if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Redis:getConnect] set keepalive ok.")) end
            end
        end
        return r,nil;
    end     
end

function Redis:close(connect)
    if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg( string.format("[Redis:close] self.datasource.pool_size = %s ,max_idle_timeout =%s",self.datasource.pool_size,self.datasource.max_idle_timeout))) end
    db_monitor.sub("redis_connect")
    if connect == nil then
        return
    end
   
    if self.datasource.pool_size >0 then
       
        -- 将连接放入到连接池中，下次申请直接从连接池中获取
        local ok, err = connect:set_keepalive( self.datasource.max_idle_timeout,self.datasource.pool_size)
        if not ok then
            ngx.log(ngx.ERR, logger.formatMsg("[Redis:close] set keepalive failed : ", err))
        else
            if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG, logger.formatMsg("[Redis:close] set keepalive ok.")) end
        end
    end
end

local commands = {
    "append",            "auth",              "bgrewriteaof",
    "bgsave",            "bitcount",          "bitop",
    "blpop",             "brpop",
    "brpoplpush",        "client",            "config",
    "dbsize",
    "debug",             "decr",              "decrby",
    "del",               "discard",           "dump",
    "echo",
    "eval",              "exec",              "exists",
    "expire",            "expireat",          "flushall",
    "flushdb",           "get",               "getbit",
    "getrange",          "getset",            "hdel",
    "hexists",           "hget",              "hgetall",
    "hincrby",           "hincrbyfloat",      "hkeys",
    "hlen",
    "hmget",             "hmset",             "hscan",
    "hset",
    "hsetnx",            "hvals",             "incr",
    "incrby",            "incrbyfloat",       "info",
    "keys",
    "lastsave",          "lindex",            "linsert",
    "llen",              "lpop",              "lpush",
    "lpushx",            "lrange",            "lrem",
    "lset",              "ltrim",             "mget",
    "migrate",
    "monitor",           "move",              "mset",
    "msetnx",            "multi",             "object",
    "persist",           "pexpire",           "pexpireat",
    "ping",              "psetex",            "psubscribe",
    "pttl",
    "publish",          "punsubscribe",       "pubsub",
    "quit",
    "randomkey",         "rename",            "renamenx",
    "restore",
    "rpop",              "rpoplpush",         "rpush",
    "rpushx",            "sadd",              "save",
    "scan",              "scard",             "script",
    "sdiff",             "sdiffstore",
    "select",            "set",               "setbit",
    "setex",             "setnx",             "setrange",
    "shutdown",          "sinter",            "sinterstore",
    "sismember",         "slaveof",           "slowlog",
    "smembers",          "smove",             "sort",
    "spop",              "srandmember",       "srem",
    "sscan",
    "strlen",       --[[ "subscribe", ]]      "sunion",
    "sunionstore",       "sync",              "time",
    "ttl",
    "type",              "unsubscribe",       "unwatch",
    "watch",             "zadd",              "zcard",
    "zcount",            "zincrby",           "zinterstore",
    "zrange",            "zrangebyscore",     "zrank",
    "zrem",              "zremrangebyrank",   "zremrangebyscore",
    "zrevrange",         "zrevrangebyscore",  "zrevrank",
    "zscan",
    "zscore",            "zunionstore",       "evalsha"
}

for i = 1, #commands do
    local cmd = commands[i]
    Redis[cmd] = function(self, ...)
        local connect = self:getConnect()
        if not connect then
            return nil
        end
        -- exec cmd
        local res, err = connect[cmd](connect, ...)
        -- close
        if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("redis get =%s ,err=%s",res,err))) end
        if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("redis will close %s ",connect))) end
        self:close(connect)
        return res, err
    end
end

function Redis:subscribe(channel)
    local connect = self:getConnect()
    if not connect then
        return nil
    end
    local res, err = connect:subscribe(channel)
    if not res then
        return nil, err
    end
    local function do_read_func(do_read)
        if do_read == nil or do_read == true then
            res, err = connect:read_reply()
            if not res then
                return nil, err
            end
            return res
        end
        connect:unsubscribe(channel)
        self:close(connect)
        return
    end
    return do_read_func
end



return Redis